package 链表;

public class Solution160 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2, node1);
        ListNode node3 = new ListNode(6, node2);
        ListNode node4 = new ListNode(3, node3);
        ListNode node5 = new ListNode(2, node4);
        ListNode node = getIntersectionNode(node5, node4);
        System.out.println(node);
    }

    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) {
            return null;
        }
        if (headA == headB) {
            return headA;
        }
        ListNode preA = headA;
        ListNode preB = headB;
        int lenA = 0;
        int lenB = 0;

        while (preA != null) {
            preA = preA.next;
            lenA++;
        }
        while (preB != null) {
            preB = preB.next;
            lenB++;
        }
        int cha = 0;
        ListNode preAA = headA;
        ListNode preBB = headB;

        if (lenA > lenB) {
            cha = lenA - lenB;
            for (int i = 0; i < cha; i++) {
                preAA = preAA.next;
            }
        } else if (lenA < lenB) {
            cha = lenB - lenA;
            for (int i = 0; i < cha; i++) {
                preBB = preBB.next;
            }
        }

        ListNode result = null;
        while (preAA != null && preBB != null) {
            if (preAA == preBB) {
                result = preAA.next;
                break;
            }
            preAA = preAA.next;
            preBB = preBB.next;

        }
        return result;
    }
}
